package com.hxzy.apsect;

import com.alibaba.fastjson.JSON;
import com.hxzy.mapper.OperateLogMapper;
import com.hxzy.pojo.OperateLog;
import com.hxzy.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * @author wzm
 * @create 2024-03-12 16:39
 * project_name:JavaWeb2401
 * @Description
 */
//AOP 实现：操作人、操作时间、执行方法的全类名、执行方法名、方法运行时参数、返回值、方法执行时长
@Component
@Aspect
@Slf4j
public class LogAspect {
    //request对象已经在ioc中可以直接获得
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private OperateLogMapper operateLogMapper;
    
    
    @Around("@annotation(com.hxzy.annoation.Log)") //对方法上有Log的方法进行增强
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {
        //开始时间
        long begin = System.currentTimeMillis();

        //操作时间
        LocalDateTime time = LocalDateTime.now();

        //操作人 ID
        //获取请求头中jwt解析令牌
        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseJwt(token);
        Integer userId = (Integer) claims.get("id");
        log.info("操作人ID:{}", userId);
        
        //操作类名
        String className = joinPoint.getTarget().getClass().getName();
        
        //操作方法名
        String methodName = joinPoint.getSignature().getName();

        //操作参数
        Object[] args = joinPoint.getArgs();
        String methodParams = Arrays.toString(args);
        
        //方法返回值
        Object result = joinPoint.proceed();
        String returnValue = JSON.toJSONString(result);

        //结束时间
        long end = System.currentTimeMillis();


        //方法执行时长
       long logTime =  end - begin;

       //就所有得到的日志信息添加到数据库中的
        OperateLog operateLog = new OperateLog(null,userId,time,className,methodName,methodParams,returnValue,logTime);
      log.info("操作日志对象{}",operateLog);
        operateLogMapper.insertLog(operateLog);
       return result;//返回原始方法的返回值
    }
}
